package clock;

import java.util.Iterator;
import java.util.Vector;

import view.Launch;

import listener.ReachedZeroEvent;
import listener.ReachedZeroListener;

public class Clock implements Runnable {
	private final static int LIMIT = 0;
	private final static int ME_WAIT_LONG_TIME = 100;

	private Minute minute;
	private Second second;
	
	private Thread thread;
	private Vector<ReachedZeroListener> listeners;
	
	public Clock(int minute, int second) {
		this.minute = new Minute(minute);
		this.second = new Second(second, this.minute);
		
		listeners = new Vector<ReachedZeroListener>();
		
		thread = new Thread(this);
		thread.start();
	}
	
	public Minute getMinute() {
		return minute;
	}
	
	public Second getSecond() {
		return second;
	}
	
	public void createEvent() {
		ReachedZeroEvent e = new ReachedZeroEvent(this);
		Iterator<ReachedZeroListener> i = listeners.iterator();
		while (i.hasNext())
			i.next().reachedZero(e);
	}
	
	public void addReachedZeroListener(ReachedZeroListener e) {
		if (listeners.contains(e))
			return;
		listeners.add(e);
	}
	
	public void removeReachedZeroListener(ReachedZeroListener e) {
		if (!listeners.contains(e))
			return;
		listeners.remove(e);
	}
	
	public void removeReachedZeroListeners() {
		if (listeners != null)
			listeners.clear();
	}
	
	public void run() {
		while (true) {
			if (timeIsUp()) {
				createEvent();
				break;
			} try {
				Thread.sleep(ME_WAIT_LONG_TIME);
			} catch (InterruptedException e) {
				if (Launch.DEBUG) e.printStackTrace();
			}
		}
	}

	public boolean timeIsUp() {
		return minute.count <= LIMIT && second.count <= LIMIT;
	}
	
	public String toString() {
		return minute + ":" + second;
	}
}
